import React, { useEffect, useState } from'react';
import useLocalStorage from '../utils/useLocalStorage';

interface SearchProps {
  params: {
    word: string;
  };
  setParams: React.Dispatch<React.SetStateAction<any>>;
}

const Search: React.FC<SearchProps> = ({ params, setParams }) => {
  const [searchHistory, setSearchHistory] = useLocalStorage<string[]>('searchHistory', []);
  const [isPanelVisible, setIsPanelVisible] = useState(false);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (params.word.trim()) {
      setParams((prev: any) => ({ ...prev, page: 1 }));
      setSearchHistory((prev: string[]) => [...new Set([params.word, ...prev])]);
      setIsPanelVisible(true); // 提交后显示搜索历史面板
      // 点击回车后让输入框失去焦点
      const inputElement = document.querySelector('.search-input');
      if (inputElement) {
        (inputElement as HTMLInputElement).blur();
      }
    }
  };

  const handleClear = () => {
    setParams((prev: any) => ({ ...prev, word: '', page: 1 }));
    setIsPanelVisible(false); // 清空搜索内容时隐藏搜索历史面板
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setParams((prev: any) => ({ ...prev, word: e.target.value }));
    // 当输入框有内容时，设置为点击状态，显示搜索历史面板
    if (e.target.value.trim()) {
      setIsPanelVisible(true);
    }
  };

  const clearHistory = () => {
    setSearchHistory([]);
    window.localStorage.removeItem('searchHistory'); // 确保本地存储也被清空
  };

  const removeHistoryItem = (item: string) => {
    setSearchHistory((prev: string[]) => prev.filter((history) => history!== item));
  };

  const handleFocus = () => {
    if (searchHistory.length > 0) {
      setIsPanelVisible(true);
    }
  };

  useEffect(() => {
    const handleDocumentClick = (event: MouseEvent) => {
      const searchPanel = document.querySelector('.search-panel');
      const searchInput = document.querySelector('.search-input');
      const isClickInsidePanel = searchPanel && searchPanel.contains(event.target as Node);
      const isClickInsideInput = searchInput && searchInput.contains(event.target as Node);

      if (!isClickInsidePanel &&!isClickInsideInput) {
        setIsPanelVisible(false);
      }
    };

    document.addEventListener('click', handleDocumentClick);
    return () => {
      document.removeEventListener('click', handleDocumentClick);
    };
  }, []);

  return (
    <div className="search-container">
      <div className={`search__bar ${isPanelVisible && searchHistory.length > 0? 'is-focus' : ''}`}>
        <form id="nav-searchform" className={`search-form ${isPanelVisible && searchHistory.length > 0? 'is-focus' : ''}`} onSubmit={handleSubmit}>
          <div
            className={`search-content ${isPanelVisible? 'clicked' : ''}`}
            onClick={() => setIsPanelVisible(true)}
          >
            <input
              type="text"
              className="search-input"
              placeholder="搜索课程"
              value={params.word}
              onChange={handleChange}
              onFocus={handleFocus}
              autoComplete="off"
              maxLength={100}
            />
            {params.word && (
              <div
                className="nav-search-clean"
                style={{ display: params.word? 'flex' : 'none', marginRight: '10px' }}
                onClick={handleClear}
              >
                <svg width="16" height="16" viewBox="0 0 16 16">
                  <path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M8 14.75C11.7279 14.75 14.75 11.7279 14.75 8C14.75 4.27208 11.7279 1.25 8 1.25C4.27208 1.25 1.25 4.27208 1.25 8C1.25 11.7279 4.27208 14.75 8 14.75ZM9.64999 5.64303C9.84525 5.44777 10.1618 5.44777 10.3571 5.64303C10.5524 5.83829 10.5524 6.15487 10.3571 6.35014L8.70718 8.00005L10.3571 9.64997C10.5524 9.84523 10.5524 10.1618 10.3571 10.3571C10.1618 10.5523 9.84525 10.5523 9.64999 10.3571L8.00007 8.70716L6.35016 10.3571C6.15489 10.5523 5.83831 10.5523 5.64305 10.3571C5.44779 10.1618 5.44779 9.84523 5.64305 9.64997L7.29296 8.00005L5.64305 6.35014C5.44779 6.15487 5.44779 5.83829 5.64305 5.64303C5.83831 5.44777 6.15489 5.44777 6.35016 5.64303L8.00007 7.29294L9.64999 5.64303Z"
                    fill="var(--Ga3)"
                  />
                </svg>
              </div>
            )}
          </div>
          <div className="search-btn">
            <svg width="17" height="17" viewBox="0 0 17 17" fill="none">
              <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M16.3451 15.2003C16.6377 15.4915 16.4752 15.772 16.1934 16.0632C16.15 16.1279 16.0958 16.1818 16.0525 16.2249C15.7707 16.473 15.4456 16.624 15.1854 16.3652L11.6848 12.8815C10.4709 13.8198 8.97529 14.3267 7.44714 14.3267C3.62134 14.3267 0.5 11.2314 0.5 7.41337C0.5 3.60616 3.6105 0.5 7.44714 0.5C11.2729 0.5 14.3943 3.59538 14.3943 7.41337C14.3943 8.98802 13.8524 10.5087 12.8661 11.7383L16.3451 15.2003ZM2.13647 7.4026C2.13647 10.3146 4.52083 12.6766 7.43624 12.6766C10.3517 12.6766 12.736 10.3146 12.736 7.4026C12.736 4.49058 10.3517 2.1286 7.43624 2.1286C4.50999 2.1286 2.13647 4.50136 2.13647 7.4026Z"
                fill="currentColor"
              />
            </svg>
          </div>
        </form>
        {isPanelVisible && searchHistory.length > 0 && (
          <div className="search-panel">
            <div className="history" style={{ maxWidth: '440px' }}>
              <div className="header">
                <div className="title">搜索历史</div>
                <div className="clear" onClick={clearHistory}>清空</div>
              </div>
              <div className="histories-wrap" style={{ maxHeight: '172px' }}>
                <div className="histories">
                  {searchHistory.map((item, index) => (
                    <div key={index} tabIndex={0} className="history-item">
                      <div className="history-text" onClick={() => setParams((prev: any) => ({ ...prev, word: item, page: 1 }))}>{item}</div>
                      <div className="close" onClick={() => removeHistoryItem(item)}>
                        <svg viewBox="0 0 1024 1024" width="14" height="14">
                          <path d="M512 64.303538c-247.25636 0-447.696462 200.440102-447.696462 447.696462 0 247.254314 200.440102 447.696462 447.696462 447.696462s447.696462-200.440102 447.696462-447.696462S759.25636 64.303538 512 64.303538zM710.491727 665.266709c12.491499 12.491499 12.489452 32.729425-0.002047 45.220924-6.246261 6.246261-14.429641 9.370415-22.611997 9.370415s-16.363689-3.121084-22.60995-9.366322L512 557.222971 358.730221 710.491727 c-6.246261 6.246261-14.429641 9.366322-22.611997 9.366322s-16.365736-3.125177-22.611997-9.370415 c-12.491499-12.491499-12.491499-32.729425 0-45.220924l153.268756-153.266709L313.50725 358.730221 c-12.491499-12.491499-12.489452-32.729425 0.002047-45.220924s32.729425-12.495592 45.220924-0.004093 l153.268756 153.268756 153.268756-153.268756c12.491499-12.491499 32.729425-12.487406 45.220924 0.004093s12.493545 32.729425 0.002047 45.220924L557.225017 512 710.491727 665.266709z" />
                        </svg>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Search;